package com.photography.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photography.entity.PageResult;
import com.photography.mapper.CustomerMapper;
import com.photography.mapper.OrderMapper;
import com.photography.mapper.SerialMapper;
import com.photography.pojo.Customer;
import com.photography.pojo.Order;
import com.photography.pojo.OrderVo;
import com.photography.pojo.Serial;
import com.photography.service.OrderService;
import com.photography.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private SerialMapper serialMapper;

    @Autowired
    private IdWorker idWorker;

    private String orderId;


    @Override
    public void addOrder(OrderVo orderVo) {
        String orderId=idWorker.nextId() + "";

        List<String> serialIds = orderVo.getSerialIds();
        if(!CollectionUtils.isEmpty(serialIds) && serialIds.size() > 0){
            for (String serialId : serialIds) {
                orderMapper.addSerialIdAndOrderId(serialId,orderId);
            }
        }
        List<String> productIds = orderVo.getProductIds();
        if(!CollectionUtils.isEmpty(productIds) && productIds.size() > 0){
            for (String productId : productIds) {
                orderMapper.addProductIdAndOrderId(productId,orderId);
            }
        }
        Order order = orderVo.getOrder();
        if (order !=null){
            order.setId(orderId);
            order.setCreatetime(new Date());
            orderMapper.insert(order);
        }

    }

    @Override
    public Order findById(String id) {
        Order order = orderMapper.selectById(id);
        return order;
    }

//    @Override
//    public PageResult<Order> findAll(Order order,int page, int rows) {
//        Page<Order> orderPage = new Page<Order>(page,rows);
//        if (order.getStarttime() != null && order.getEndtime() != null){
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//             String starttimeString = formatter.format(order.getStarttime());
//            String endttimeString = formatter.format(order.getEndtime());
//            List<Order> orderList = orderMapper.selectByStartTimeAndEndTime(starttimeString,endttimeString);
//            for (Order o1:orderList){
//                Customer customer1 = customerMapper.selectById(o1.getCustomerid());
//                List<Serial> serialList3 = serialMapper.findSerialByOrderId(o1.getId());
//                HashMap<String, String> map3 = new HashMap<>();
//                if (!CollectionUtils.isEmpty(serialList3)){
//                    for (Serial serial:serialList3){
//                        map3.put("名称:"+serial.getSerialname()+"  价格",serial.getSerialprice().toString());
//                    }
//                    o1.setSerialname(JSON.toJSONString(map3).replace("\"","").replace(","," | ").replace("{","").replace("}",""));
//                }
////              System.out.println(JSON.toJSONString(map2).replace("\"","").replace(","," | ").replace("{","").replace("}",""));
//                o1.setCustomer(customer1);
//            }
//            orderPage.setRecords(orderList);
//        } else if (!StringUtils.isEmpty(order.getId())){
//              ArrayList<Order> list = new ArrayList<>();
//              Order order1 = orderMapper.selectById(order.getId());
//              Customer customer = customerMapper.selectById(order1.getCustomerid());
//              List<Serial> serialList = serialMapper.findSerialByOrderId(order1.getId());
//              HashMap<String, String> map1 = new HashMap<>();
//              for (Serial serial : serialList){
//                  map1.put("名称:"+serial.getSerialname()+"  价格",serial.getSerialprice().toString());
//              }
//              order1.setSerialname(JSON.toJSONString(map1).replace("\"","").replace(","," | ").replace("{","").replace("}",""));
//             /* System.out.println(JSON.toJSONString(map1));*/
//              order1.setCustomer(customer);
//              list.add(order1);
//              orderPage.setRecords(list);
//      }else {
//          EntityWrapper<Order> wrapper = new EntityWrapper<>();
//          wrapper/*.eq("state",0).or().eq("state",1)*/
//                  .like(null != order.getAppointmenttimestring(),"appointmenttime",order.getAppointmenttimestring())
//                  .like(null != order.getMakephototimestring(),"makephototime",order.getMakephototimestring())
//                  .like(null != order.getDesigntimestring(),"designtime",order.getDesigntimestring())
//                  .orderBy("appointmenttime");
//          List<Order> orders = orderMapper.selectPage(orderPage, wrapper);
//          for (Order o:orders){
//              Customer customer1 = customerMapper.selectById(o.getCustomerid());
//              List<Serial> serialList2 = serialMapper.findSerialByOrderId(o.getId());
//              HashMap<String, String> map2 = new HashMap<>();
//              if (!CollectionUtils.isEmpty(serialList2)){
//                  for (Serial serial:serialList2){
//                      map2.put("名称:"+serial.getSerialname()+"  价格",serial.getSerialprice().toString());
//                  }
//                  o.setSerialname(JSON.toJSONString(map2).replace("\"","").replace(","," | ").replace("{","").replace("}",""));
//              }
////              System.out.println(JSON.toJSONString(map2).replace("\"","").replace(","," | ").replace("{","").replace("}",""));
//              o.setCustomer(customer1);
//          }
//          orderPage.setRecords(orders);
//      }
//
//        PageResult<Order> orderPageResult = new PageResult<Order>();
//        orderPageResult.setTotal(orderPage.getTotal());
//        orderPageResult.setRows(orderPage.getRecords());
//        return orderPageResult;
//    }

    @Override
    public void addSerialByIds(String[] ids) {
        orderId = idWorker.nextId() + "";
        Order order = new Order();
        order.setId(orderId);
        orderMapper.insert(order);
        for (String id : ids){
                orderMapper.addSerialIdAndOrderId(id,order.getId());
            }

    }

    @Override
    public void updateOrder(OrderVo orderVO) {
        orderMapper.updateById(orderVO.getOrder());
        List<String> serialIds = orderVO.getSerialIds();
        orderMapper.deleteSerialIdsByOrderId(orderVO.getOrder().getId());
        if (!CollectionUtils.isEmpty(serialIds) && serialIds.size() > 0){
            for (String serialId : serialIds) {
                if (!StringUtils.isEmpty(serialId)){
                    orderMapper.addSerialIdAndOrderId(serialId,orderVO.getOrder().getId());
                }

            }
        }
        List<String> productIds = orderVO.getProductIds();
        orderMapper.deleteProductIdsByOrderId(orderVO.getOrder().getId());
        if (!CollectionUtils.isEmpty(productIds) && productIds.size() > 0){
            for (String productId : productIds) {
                if (!StringUtils.isEmpty(productId)){
                    orderMapper.addProductIdAndOrderId(productId,orderVO.getOrder().getId());
                }

            }
        }
    }


    @Override
    public PageResult<Order> findAll(Order order, Integer page, Integer size) {
        Page<Order> p = new Page<>(page, size);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper
                .eq(order.getId() != null,"id",order.getId())
                .eq(order.getStatus()!=null,"status",order.getStatus())
                .apply(!StringUtils.isEmpty(order.getStarttime()),
                        "date_format (appointmenttime,'%Y-%m-%d') >= date_format('" + order.getStarttime() + "','%Y-%m-%d')")
                .apply(!StringUtils.isEmpty(order.getEndtime()),
                        "date_format (appointmenttime,'%Y-%m-%d') <= date_format('" + order.getEndtime() + "','%Y-%m-%d')");
        if (!StringUtils.isEmpty(order.getChangecustomstate()) && order.getChangecustomstate().equals("0")){
            wrapper .apply("date_format (appointmenttime,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d')");
        }
        if (!StringUtils.isEmpty(order.getChangecustomstate()) && order.getChangecustomstate().equals("1")){
            wrapper .apply("date_format (appointmenttime,'%Y-%m-%d') > date_format(now(),'%Y-%m-%d')");
        }
        Page<Order> orderPage = orderMapper.selectPage(p, wrapper);
        if (!CollectionUtils.isEmpty(orderPage.getRecords())){
            for (Order or : orderPage.getRecords()) {
                Customer customer = new Customer();
                customer.setId(or.getCustomerid());
                customer = customerMapper.selectById(customer);
                or.setCustomer(customer);
            }
        }
        PageResult<Order> orderPageResult = new PageResult<>();
        orderPageResult.setRows(orderPage.getRecords());
        orderPageResult.setTotal(orderPage.getTotal());
        return orderPageResult;
    }

    @Override
    public OrderVo getById(String id) {
        OrderVo orderVo = new OrderVo();
        Order selectOrder = new Order();
        selectOrder.setId(id);
        Order order = orderMapper.selectById(selectOrder);
        orderVo.setOrder(order);
        List<String> serialIds = orderMapper.selectSerialIdByOrderId(id);
        if (!CollectionUtils.isEmpty(serialIds)){
            orderVo.setSerialIds(serialIds);
        }
        List<String> productIds= orderMapper.selectProductIdByOrderId(id);
        if (!CollectionUtils.isEmpty(productIds)){
            orderVo.setProductIds(productIds);
        }
        return orderVo;
    }

    @Override
    public void deleteOrder(String id) {
        Order order = new Order();
        order.setId(id);
        order.setState(2);
        orderMapper.updateById(order);
    }

    @Override
    public void updateOrderByState(Order order) {
        orderMapper.updateById(order);
    }

}
